
import javax.swing.text.Element;

/**This class divides 1 SmallDocuments(SDs)into 2 SDs
 * 
 */

/**
 * @author u0907023
 *
 */
public class Divide extends Command
{

	public SmallDocument sd;
	public SmallDocument sd2;
	
	
	public Divide(Stylepad editor, SmallDocument sd1, SmallDocument sd2) {
		
		this.editor = editor;
		this.sd = sd1;
		this.sd2 = sd2;
		
	}

	@Override
	public void process() {
		
		synchronized(editor){
			synchronized(sd){
				
				//int baseLine = SDAction.getSDLines(editor, sd)/2;
				int baseLine = SDAction.getSDLines(editor, sd);
				Element e = editor.getEditor().getDocument().getDefaultRootElement().getElement(sd.firstParaIndex);
				
				int curTotal = SDAction.countLines(editor, e.getStartOffset(), e.getEndOffset());
				
				int i = 0;
				for(; i < sd.numberOfParas -1; i++){
					
					e = editor.getEditor().getDocument().getDefaultRootElement().getElement(sd.firstParaIndex + i + 1);
					int next = SDAction.countLines(editor, e.getStartOffset(), e.getEndOffset());
					
					if(curTotal + next > baseLine)
						break;
					
					curTotal += next;
				}
				
				sd2.firstParaIndex = sd.firstParaIndex + (i + 1);
				sd2.numberOfParas = sd.numberOfParas - (i+1);
				sd2.lockingStatus = SmartManager.LOCKED_BY_ME;
				int noLines = SDAction.getSDLines(editor, sd2);
				sd2.docName = SDAction.updateLineNoInFileName(sd2.docName, noLines);
				
				sd.numberOfParas = i + 1;
				noLines = SDAction.getSDLines(editor, sd);
				sd.docName = SDAction.updateLineNoInFileName(sd.docName, noLines);
				if(sd.isModified)
					sd.isModified = false;
				
			}
		}	
	}	
}
